package com.yan.demo;

import com.yan.demo.domain.Student;

import java.io.*;
import java.util.ArrayList;

/**
 * @author taoge
 * @Date 2024/8/6 15:51
 * @Description 对象克隆
 */
public class Demo5 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Student stu = new Student("张三", 18);
        Student newStu = cloneObj(stu);
        System.out.println(newStu);
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("张三" , 18));
        list.add(new Student("李四" , 20));
        list.add(new Student("王五" , 21));
        ArrayList<Student> newList = cloneObj(list);
        for (Student student : newList) {
            System.out.println(student);
        }
    }

    public static<T> T cloneObj(T t) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(t);
        oos.flush();
        oos.close();
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
        T newT = (T) ois.readObject();
        ois.close();
        return newT;
    }
}
